let fs = require('fs');
let path = require('path');
// 异步版
function wide(p,callback){
    let arr = [p];
    let index = 0;
    let current;//当前值
    // 递归将文件夹加入数组
    function next(index){
        current = arr[index];
        if (current != undefined) {
            fs.stat(current,function(err,statObj){
                if (statObj.isDirectory()) {
                    fs.readdir(current,function(err,dirs){
                        dirs = dirs.map(dir=>path.join(current,dir));
                        arr = [...arr,...dirs];
                        next(++index);
                    })
                }else{
                    fs.unlink(current,function(){
                        next(index);
                    })
                }
            });
        }else{
            return step(index);
        }
    }; 
    // 递归删除文件夹
    function step(index){
        if(index == 0)return callback();
        current = arr[--index];
        fs.rmdir(current,function(){
            step(index);
        });
    }
    next(index);
    
}

// promise版
function wide(p){
    return new Promise((resolve,reject)=>{
        let arr = [p];
        let index = 0;
        let current;//当前值
        // 递归将文件夹加入数组
        function next(index){
            current = arr[index];
            if (current != undefined) {
                fs.stat(current,function(err,statObj){
                    if (statObj.isDirectory()) {
                        fs.readdir(current,function(err,dirs){
                            dirs = dirs.map(dir=>path.join(current,dir));
                            arr = [...arr,...dirs];
                            next(++index);
                        })
                    }else{
                        fs.unlink(current,function(){
                            next(index);
                        })
                    }
                });
            }else{
                return step(index);
            }
        }; 
        // 递归删除文件夹
        function step(index){
            if(index == 0) return resolve;
            current = arr[--index];
            fs.rmdir(current,function(){
                step(index);
            });
        }
        next(index);
    });
}


// async await版
let {promisify} = require('util');
let stat = promisify(fs.stat);
let readdir = promisify(fs.readdir);
let unlink = promisify(fs.unlink);
let rmdir = promisify(fs.rmdir);

async function wide(p){
    let arr = [p];
    let index = 0;
    let current;
    while(current = arr[index]){
        let statObj = await stat(current);
        if (statObj.isDirectory()) {
            let dirs = await readdir(current);
            dirs = dirs.map(dir=>path.join(current,dir));
            arr = [...arr,...dirs];
            index++;
        }else{
            await unlink(current);
        }
    }
    let cur;
    while(cur = arr[--index]){
        await rmdir(cur);
    }
}